package org.xian.common;

import com.google.protobuf.Message;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommandManager {

    static Map<Integer, Class<?>> requestMaps = null;

    static Map<Integer, Class<?>> responseMaps = null;

    static {
        // Protobuf 编译后的 Java 文件所在的包名
        String packageName = "org.xian.common.proto";
        Class clazz = Message.class;
        requestMaps = getCommandMaps(packageName, "Request_");
        responseMaps = getCommandMaps(packageName, "Response_");
    }

    static Map<Integer, Class<?>> getCommandMaps(String packageName, String type) {
        HashMap<Integer, Class<?>> map = new HashMap<>();
        try {
            List<Class<?>> classes = ClassUtils.getClasses(packageName);
            for (Class<?> aClass : classes) {
                // 继承自com.google.protobuf.Message 的才是
                if (Message.class.isAssignableFrom(aClass) && !Message.class.equals(aClass)) {
                    String name = aClass.getSimpleName();
                    if (name.contains(type)) {
                        int cmd = Integer.parseInt(name.split("_")[1]);
                        map.put(cmd, aClass);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Class<?> getRequestClass(int cmd) {
        return requestMaps.get(cmd);
    }

    public static void main(String[] args) {
        Class<?> aClass = responseMaps.get(100101);
        System.out.println(aClass.getSimpleName());
    }
}
